package cn.lele.reggie.service.impl;

import cn.lele.reggie.common.BaseContext;
import cn.lele.reggie.common.R;
import cn.lele.reggie.dto.OrdersDto;
import cn.lele.reggie.entity.*;
import cn.lele.reggie.mapper.OrderMapper;
import cn.lele.reggie.service.*;
import cn.lele.reggie.vo.TurnoverReportVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Resource
    OrderMapper orderMapper;

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private DishService dishService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;
    /**
     * 统计指定时间区间内的营业额数据
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO prepareData(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        while (!begin.equals(end)) {
            //日期计算，计算指定日期的后一天对应的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //存放每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询date日期对应的营业额数据，营业额是指：状态为“已完成”的订单金额合计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // select sum(amount) from orders where order_time > beginTime and order_time < endTime and status = 4
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", 4);//订单已完成
            Double turnover = orderMapper.sumByMap(map);

            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(dateList);
        turnoverReportVO.setTurnoverList(turnoverList);
        return turnoverReportVO;

        //封装返回结果
//        return TurnoverReportVO
//                .builder()
//                .dateList(StringUtils.join(dateList, ","))
//                .turnoverList(StringUtils.join(turnoverList, ","))
//                .build();
    }

    @Override
    public R<String> submitOrder(OrdersDto orders) {
        log.info("orderDto---->"+orders);
        Long userId = BaseContext.getCurrentId();
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(1);//设置为待接单
        //设置价钱
        BigDecimal amount=new BigDecimal(0);
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(shoppingCartLambdaQueryWrapper);
        for (ShoppingCart shoppingCart : shoppingCartList) {
            log.info("价钱："+shoppingCart.getAmount());
            amount=amount.add(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())));
            //销量+1
            if(shoppingCart.getSetmealId()!=null){
                Setmeal setmeal = setmealService.getById(shoppingCart.getSetmealId());
                LambdaUpdateWrapper<Setmeal> setmealLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                setmealLambdaUpdateWrapper.set(Setmeal::getSaleNum,setmeal.getSaleNum()+1)
                        .eq(Setmeal::getId,shoppingCart.getSetmealId());
                setmealService.update(setmealLambdaUpdateWrapper);
            }
            if(shoppingCart.getDishId()!=null){
                Dish dish = dishService.getById(shoppingCart.getDishId());
                LambdaUpdateWrapper<Dish> dishLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                dishLambdaUpdateWrapper.set(Dish::getSaleNum,dish.getSaleNum()+1)
                        .eq(Dish::getId,shoppingCart.getDishId());
                dishService.update(dishLambdaUpdateWrapper);
            }
        }
        log.info("总价钱——————"+amount);
        orders.setAmount(amount);
        //设置地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        //设置用户名
        User user = userService.getById(userId);
        orders.setUserName(user.getName());
        //保存并设置订单号
        this.save(orders);
        orders.setNumber(orders.getId().toString());
        //设置订单细节（菜品+口味）
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orders.getId());
            if(shoppingCart.getDishId()!=null){
                orderDetail.setDishId(shoppingCart.getDishId());
            }
            if (shoppingCart.getSetmealId()!=null){
                orderDetail.setSetmealId(shoppingCart.getSetmealId());
            }
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setAmount(shoppingCart.getAmount());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetailService.save(orderDetail);
        }
        this.updateById(orders);
        return R.success("下单成功");
    }

    @Override
    public R<Page> pageOrders(Integer page, Integer pageSize) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId,BaseContext.getCurrentId()).orderByDesc(Orders::getOrderTime);
        this.page(ordersPage,ordersLambdaQueryWrapper);
        //赋值过去，增强
        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        ArrayList<OrdersDto> ordersDtos = new ArrayList<>();
        //对每一个订单设置相关参数
        for (Orders record : ordersPage.getRecords()) {
            //从detail加上num
            Integer sumNum= 0 ;
            OrdersDto dto = new OrdersDto();
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId,record.getId());
            List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);
            for (OrderDetail orderDetail : orderDetailList) {
                sumNum+=orderDetail.getNumber();
            }
            BeanUtils.copyProperties(record,dto);
            dto.setSumNum(sumNum);
            dto.setOrderDetails(orderDetailList);
            ordersDtos.add(dto);
        }
        ordersDtoPage.setRecords(ordersDtos);
        return R.success(ordersDtoPage);
    }

}
